import ai
import db
from wxauto import *
import time

wx = WeChat()

listen_list = [] 

# 读取好友列表
file_path = 'names.txt'
try:
    with open(file_path, 'r', encoding='utf-8') as file:
        names = file.readlines() 
        listen_list = [name.strip() for name in names]

except FileNotFoundError:
    print(f"文件 {file_path} 未找到，请检查文件路径是否正确！")
except Exception as e:
    print(f"读取文件时发生错误：{e}")

for i in listen_list:
    print(f"开始监听好友 {i} 的消息...")
    wx.AddListenChat(who=i, savepic=False)

wait = 1  # 设置间隔时间

# 创建数据库
db.create_db()

def check_for_sylvester(s):
    if s.startswith('@Sylvester﹌'):
        return 1
    if s.endswith('@Sylvester﹌'):
        return 2
    else:
        return 0

def help_info():
    info = '''
Sylvester﹌ AI助理使用说明：

- 回答问题
  回复 @Sylvester﹌+问题
  说明：针对当前这一条消息，AI助理会给出回答

- 多消息回复
  最后一条消息+ @Sylvester﹌
  说明：你可以一次性发送多条消息，AI助理会根据你的所有消息进行回复
  
- 清空历史对话
  回复 @Sylvester﹌ 清空历史对话
    '''
    return info

while True:
    try:
        msgs = wx.GetListenMessage()
        for chat in msgs:
            who = chat.who  # 获取聊天窗口名（人或群名）
            one_msgs = msgs[chat]  # 获取消息内容

            last_msg = one_msgs[-1]
            sender = last_msg.sender  # 获取消息发送者

            # 保存历史记录
            for msg in one_msgs:
                db.add_history_sender(who, "user", msg.sender,msg.content)
            print("-----------------"*2)

            should_reply_msgs = {}
            # 检测是否有关键词
            for msg in one_msgs:
                key = msg.sender
                val = msg
                print(f'【{who}】 {key}：{val}')
                if check_for_sylvester(val.content)>0:
                    should_reply_msgs[key] = val
            
            if len(should_reply_msgs) != 0:
                for sender, msg in should_reply_msgs.items():
                    if "帮助" in msg.content:
                        msg.quote(help_info())
                        print(f'【{who}】：查看帮助信息')
                        continue
                    if "清空历史对话" in msg.content:
                        db.delete_history(who,sender)
                        chat.SendMsg(" AI助理:好的，我已经帮您清空了对话内容。请问还有其他可以帮助您的吗？",at=[sender])
                        print(f'【{who}】：清空历史对话')
                        continue
                    print(f'【{who}】：检测到关键词【@Sylvester﹌】,开始AI回复...')
                    status = check_for_sylvester(msg.content)
                    ai_reply = ai.chat_sender(who, sender,status)
                    final_replay = 'AI助理:' + '\n' + ai_reply
                    print(f'AI回复【{who}】：{ai_reply}')
                    last_msg.quote(final_replay)
    except Exception as e:
        print(f"Error: {e}")
                
    time.sleep(wait)
